package com.newsmanagement.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newsmanagement.domain.pojo.*;
import com.newsmanagement.mapper.SlauWholBatchMapper;
import com.newsmanagement.service.NodeInfoService;
import com.newsmanagement.service.RetaBatchService;
import com.newsmanagement.service.SlauBatchService;
import com.newsmanagement.service.WholBatchService;
import com.newsmanagement.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wholBatch")
public class WholBatchController {

    @Autowired
    private SlauWholBatchMapper wholBatchMapper;

    @Autowired
    private WholBatchService wholBatchService;

    @Autowired
    private SlauBatchService slauBatchService;

    @Autowired
    private RetaBatchService retaBatchService;

    @Autowired
    private NodeInfoService nodeInfoService;

    /**
     * 根据状态获取批发商产品批号列表
     */
    @GetMapping("/listByState")
    public Result<List<WholBatch>> getWholBatchesByState(@RequestParam Integer state, HttpServletRequest request) {
        try {
            Integer wholId = getCurrentWholId(request);
            LambdaQueryWrapper<WholBatch> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WholBatch::getWholId, wholId)
                    .eq(WholBatch::getState, state);
            List<WholBatch> list = wholBatchService.list(queryWrapper);
            return Result.success(list);
        } catch (Exception e) {
            return Result.error("查询批号失败: " + e.getMessage());
        }
    }

    /**
     * 确认批发商产品批号（待确认 → 已确认）
     */
    @PutMapping("/confirm/{wbId}")
    public Result confirmWholBatch(@PathVariable Integer wbId, HttpServletRequest request) {
        try {
            Integer currentWholId = getCurrentWholId(request);
            WholBatch wholBatch = wholBatchService.getById(wbId);
            if (wholBatch == null) {
                return Result.error("批发商产品批号不存在");
            }

            // 检查当前状态是否为待确认（2）
            if (wholBatch.getState() != 2) {
                return Result.error("只有待确认状态的批发商产品批号才能确认");
            }

            // 校验权限（确保是当前批发商的批号）
            if (!wholBatch.getWholId().equals(currentWholId)) {
                return Result.error("无权操作该批号");
            }

            // 更新状态为已确认（3）
            wholBatch.setState(3);
            wholBatchService.updateById(wholBatch);

            return Result.success();
        } catch (Exception e) {
            return Result.error("确认失败: " + e.getMessage());
        }
    }

    // 获取所有省份
    @GetMapping("/provinces")
    public Result<List<NodeInfo>> getProvinces() {
        try {
            List<NodeInfo> provinces = nodeInfoService.getProvinces();
            return Result.success(provinces);
        } catch (Exception e) {
            return Result.error("获取省份数据失败: " + e.getMessage());
        }
    }

    // 根据省份获取城市
    @GetMapping("/cities")
    public Result<List<NodeInfo>> getCities(@RequestParam Integer provId) {
        return Result.success(nodeInfoService.getCitiesByProvId(provId));
    }

    // 根据地区获取屠宰企业
    @GetMapping("/slaughterEnterprises")
    public Result<List<NodeInfo>> getSlaughterEnterprises(@RequestParam Integer provId, @RequestParam Integer cityId) {
        return Result.success(nodeInfoService.getSlaughterByArea(provId, cityId));
    }

    // 根据屠宰企业获取批号
    @GetMapping("/slaughterBatches")
    public Result<List<SlauBatch>> getSlaughterBatches(@RequestParam Integer slauId) {
        return Result.success(slauBatchService.getBySlauId(slauId));
    }

    // 检查产品批号是否存在
    @GetMapping("/checkBatchId")
    public Result<Boolean> checkBatchId(@RequestParam String batchId) {
        boolean exists = wholBatchService.checkBatchIdExists(batchId);
        return Result.success(exists);
    }

    // 删除产品批号
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id, HttpServletRequest request) {
        // 权限校验：只能删除自己的批号
        Integer currentWholId = getCurrentWholId(request);
        WholBatch wholBatch = wholBatchService.getById(id);
        if (wholBatch == null || !wholBatch.getWholId().equals(currentWholId)) {
            return Result.error("无权删除该批号");
        }
        wholBatchService.removeById(id);
        return Result.success();
    }

    // 下架产品批号
    @PutMapping("/offline/{id}")
    public Result offline(@PathVariable Integer id, HttpServletRequest request) {
        // 权限校验
        Integer currentWholId = getCurrentWholId(request);
        WholBatch wholBatch = wholBatchService.getById(id);
        if (wholBatch == null || !wholBatch.getWholId().equals(currentWholId)) {
            return Result.error("无权操作该批号");
        }
        wholBatch.setWbId(id);
        wholBatch.setState(4); // 已下架状态
        wholBatchService.updateById(wholBatch);
        return Result.success();
    }

    // 获取详情
    @GetMapping("/detail/{id}")
    public Result<WholBatch> getDetail(@PathVariable Integer id, HttpServletRequest request) {
        // 权限校验
        Integer currentWholId = getCurrentWholId(request);
        WholBatch wholBatch = wholBatchService.getById(id);
        if (wholBatch == null || !wholBatch.getWholId().equals(currentWholId)) {
            return Result.error("无权查看该批号详情");
        }
        return Result.success(wholBatch);
    }

    // 获取下游待确认列表
    @GetMapping("/downstreamConfirm")
    public Result<List<RetaBatch>> getDownstreamConfirm(HttpServletRequest request) {
        // 使用当前登录批发商ID，避免手动传入
        Integer wholId = getCurrentWholId(request);
        return Result.success(retaBatchService.getPendingConfirmByWholId(wholId));
    }

    // 获取当前登录批发商ID（从JWT令牌中解析）
    private Integer getCurrentWholId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("未获取到令牌");
        }
        // 移除可能的Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        Map<String, Object> claims = JwtUtil.parseToken(token);
        Integer wholId = (Integer) claims.get("wholId");
        if (wholId == null) {
            throw new RuntimeException("令牌中未包含批发商ID");
        }
        return wholId;
    }

    // 1. 分页查询批发商批号（支持按状态、品种筛选）
    @GetMapping("/page")
    public Result<IPage<WholBatch>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Integer state,
            String type,
            HttpServletRequest request) {
        try {
            Integer wholId = getCurrentWholId(request);
            Page<WholBatch> page = new Page<>(pageNum, pageSize);
            // 调用Service层封装的分页查询方法（包含排序逻辑）
            IPage<WholBatch> resultPage = wholBatchService.pageQuery(page, wholId, state, type);
            return Result.success(resultPage);
        } catch (Exception e) {
            return Result.error("分页查询失败: " + e.getMessage());
        }
    }

    /**
     * 创建产品批号
     * POST /api/wholBatch/create
     * 请求头需包含 Authorization: Bearer <token>
     * 请求体为 WholBatch 对象，无需指定 wholId（自动从 token 获取）
     */
    @PostMapping("/create")
    public Result create(@Validated @RequestBody WholBatch wholBatch, HttpServletRequest request) {
        try {
            // 自动填充当前批发商ID
            wholBatch.setWholId(getCurrentWholId(request));
            // 设置屠宰企业批号ID
            if (wholBatch.getSlauBatchId() != null) {
                wholBatch.setSbId(wholBatch.getSlauBatchId());
            }
            boolean success = wholBatchService.addWholBatch(wholBatch);
            if (success) {
                return Result.success("创建成功");
            } else {
                return Result.error("产品批号已存在或创建失败");
            }
        } catch (Exception e) {
            return Result.error("创建产品批号失败: " + e.getMessage());
        }
    }

    // 3. 更新产品批号（完善参数接收，支持全量字段更新）
    @PutMapping("/update")
    public Result update(@Validated @RequestBody WholBatch wholBatch, HttpServletRequest request) {
        try {
            // 校验当前批发商权限（只能更新自己的批号）
            Integer currentWholId = getCurrentWholId(request);
            WholBatch existing = wholBatchService.getById(wholBatch.getWbId());
            if (existing == null) {
                return Result.error("批号不存在");
            }
            if (!existing.getWholId().equals(currentWholId)) {
                return Result.error("无权更新该批号");
            }
            // 禁止修改批发商ID
            wholBatch.setWholId(currentWholId);
            // 设置屠宰企业批号ID
            if (wholBatch.getSlauBatchId() != null) {
                wholBatch.setSbId(wholBatch.getSlauBatchId());
            }
            boolean result = wholBatchService.updateById(wholBatch);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新产品批号失败: " + e.getMessage());
        }
    }

    // 4. 确认下游请求（同步更新零售商批号状态）
    @PutMapping("/confirmDownstream/{retaBatchId}")
    public Result confirmDownstream(@PathVariable Integer retaBatchId, HttpServletRequest request) {
        try {
            Integer currentWholId = getCurrentWholId(request);
            RetaBatch retaBatch = retaBatchService.getById(retaBatchId);
            if (retaBatch == null) {
                return Result.error("零售商批号不存在");
            }

            // 校验权限（确保是当前批发商的下游）
            WholBatch wholBatch = wholBatchService.getById(retaBatch.getWbId());
            if (wholBatch == null || !wholBatch.getWholId().equals(currentWholId)) {
                return Result.error("无权操作该批号");
            }

            // 更新批发商状态为已确认
            wholBatch.setState(3);
            wholBatchService.updateById(wholBatch);

            // 同步更新零售商批号状态为已确认
            retaBatch.setState(3);
            retaBatchService.updateById(retaBatch);

            return Result.success();
        } catch (Exception e) {
            return Result.error("确认下游请求失败: " + e.getMessage());
        }
    }

    // 5. 按状态查询批号
    @GetMapping("/byState")
    public Result<List<WholBatch>> getByState(@RequestParam Integer state, HttpServletRequest request) {
        try {
            Integer wholId = getCurrentWholId(request);
            LambdaQueryWrapper<WholBatch> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WholBatch::getWholId, wholId)
                    .eq(WholBatch::getState, state);
            List<WholBatch> list = wholBatchService.list(queryWrapper);
            return Result.success(list);
        } catch (Exception e) {
            return Result.error("查询批号失败: " + e.getMessage());
        }
    }

}